const cartModule = {
    namespaced:true,
    state:{
        cartList:[],
        allCheck:false,
        edit:true,
        total:0
    },
    getters:{
        getCartList(_state){
            return _state.cartList
        },
        getAllCheck(_state){
            return _state.allCheck
        },
        getEdit(_state){
            return _state.edit
        },
        getTotal(_state){
            return _state.total
        }
    },
    mutations:{
        //添加购物车
        addCartList(_state,val){
            return _state.cartList.unshift(val)
        },

        //增加商品数量
        changeCount(_state,val){
            let cartFind = _state.cartList.findIndex(item=>item.id === val)
            return _state.cartList[cartFind].count ++
        },
        //减少商品数量
        reduceGoods(_state,val){
            let cartFind = _state.cartList.findIndex(item=>item.id === val)
            return _state.cartList[cartFind].count --
        },
        //改变allCheck
        changeAllCheck(_state){
                return _state.allCheck = !_state.allCheck
        },
        //删除后取消全选
        cancel(_state){
            return _state.allCheck = false
        },

        //全选
        allCheck(_state){
           return _state.cartList.map(item=>{
              return  item.check = _state.allCheck
        })
        },
        //单选
        single(_state){
            return _state.allCheck = _state.cartList.every(item => item.check === true)
        },
        // 管理/完成
        changeEdit(_state){
            if(!!_state.cartList.length){
                return _state.edit = !_state.edit
            }else{
                return _state.edit = true
            }
            
        },
        //删除单个商品
        deleteGoods(_state,val){
            return _state.cartList =  _state.cartList.filter(item=> item.id != val)
        },
        //删除选中
        deleteChecked(_state){
            return _state.cartList = _state.cartList.filter(item => item.check === false)
        },

        //合计
        total(_state){
            let __cartList = _state.cartList.filter(item => item.check === true)
            return _state.total = __cartList.reduce((num,item)=>{
                        return num += item.price * item.count
            },0)
        },


        //退出登录后清空购物车
        emptyCartList(_state){
            return _state.cartList = []
        },

        
        accessCart(_state,val){
            return _state.cartList = val
        },
        //提交订单后的购物车
        submitCart(_state){
            return _state.cartList = _state.cartList.filter(item=>item.check === false)
        },
        //提交订单后改变全选
        allCheckFalse(_state){
            _state.allCheck = false
            _state.total = 0
        }

    }
}

export default cartModule